package com.ecs.server.importdata;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class InitialConnection implements Runnable {
	
	final int hostPort = 10991;
	public static Socket socket;
	PrintWriter printWriter;
	
	private static SessionFactory factory;
	static{
		try {
			Configuration cfg = new Configuration().configure();
			factory = cfg.buildSessionFactory();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			sendInfo("auth.xml");
			receiveData();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public InitialConnection() throws Exception
	{
		InetAddress host = InetAddress.getByName("andientikli.cs.tut.fi");
		String hostIP = host.getHostAddress();
		socket = new Socket(hostIP,hostPort);
		
	}
	
	public void sendInfo(String fileName) throws Exception
	{
		printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
		File file = new File(fileName);
		BufferedReader br = new BufferedReader(new FileReader(file));
		String str = null;
		while((str = br.readLine()) != null){
			printWriter.println(str);
			printWriter.flush();
		}
	}
	
	public void receiveData() throws Exception
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String auth_response = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>";
		String str = null;
		InjectData inject = new InjectData();
		while((str = br.readLine()) != null)
		{
			if(str.equals(auth_response))
				continue;
			else if(str.equals(""))
				continue;

			File file = new File("temp.xml");
			FileWriter fileWriter = new FileWriter(file);
			PrintWriter out = new PrintWriter(new BufferedWriter(fileWriter));
			out.println(str);
			out.flush();
			out.close();
			XMLMessage xmlMessage = new XMLMessageForm().formXMLMessage(file);
			System.out.println(xmlMessage.getMessageType() + " " + xmlMessage.getMeasurementType() + " " + xmlMessage.getNormalValue());
			if(xmlMessage.getMessageType().equalsIgnoreCase("AuthenticationResponse")
					&& xmlMessage.getResponseCode().equalsIgnoreCase("200"))
			{
				sendInfo("request.xml");
				receiveData();
			}
			Session session = factory.openSession();
			inject.inject(xmlMessage, session);
		}
	}
	

}
